<template>
  <div class="login">
    <div class="loginDialog">
      <div class="title-container">
        <div class="logo-svg" />
      </div>
      <div class="loginBox">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
          <el-form-item prop="username" :class="{ active: acActive }">
            <div class="svg-container" :class="{ active: acActive }">
              <svg-icon icon-class="user-ui" class-name="tag" />
            </div>
            <el-input
              v-model="loginForm.username"
              placeholder="请输入账号"
              type="text"
              name="username"
              clearable
              tabindex="1"
              @blur="acTextOnblur"
              @keyup.native="acTextOnFocus"
            />
          </el-form-item>

          <el-form-item prop="password" :class="{ active: pwActive }">
            <div class="svg-container" :class="{ active: pwActive }">
              <svg-icon icon-class="lock-ui" class-name="tag" />
            </div>
            <el-input
              v-model="loginForm.password"
              placeholder="请输入密码"
              :type="passwordType"
              name="password"
              clearable
              tabindex="2"
              @blur="pwTextOnblur"
              @keyup.native="pwTextOnFocus"
              @keyup.enter.native="submitData"
            />
            <!-- <div class="svg-eye" @click.prevent="showPwd">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                class-name="tag"
              />
            </div>-->
          </el-form-item>

          <el-form-item
            v-show="identificationVisible"
            prop="identification"
            :class="{ active: codeActive }"
            style="width: 180px"
          >
            <!-- <div class="svg-container" :class="{ active: codeActive }">
              <svg-icon icon-class="lock" class-name="tag" />
            </div>-->
            <el-input
              v-model="loginForm.identification"
              placeholder="请输入验证码"
              style="width: 150px;padding-left: 14px;"
              type="text"
              name="identification"
              clearable
              tabindex="3"
              @blur="codeTextOnblur"
              @keyup.native="codeTextOnFocus"
              @keyup.enter.native="submitData"
            />
            <div class="codeImg" @click="getCode()">
              <img
                id="codeImg"
                :src="codeUrl"
                alt="点击更换"
                title="点击更换"
              >
            </div>
          </el-form-item>

          <div class="choosed">
            <el-checkbox v-model="autoLogin">记住密码</el-checkbox>
          </div>

          <el-button
            class="loginBtn"
            :loading="loading"
            :class="{
              active: loginForm.username && loginForm.password && loginForm.identification
            }"
            @click.prevent.stop="submitData"
          >登录系统</el-button>
        </el-form>
        <!--        <el-button class="thirdparty-button" type="primary" @click="showDialog=true">-->
        <!--          第三方登录-->
        <!--        </el-button>-->
      </div>
    </div>

    <!-- 选择机构弹框 -->
    <el-dialog
      ref="orgDialog"
      title="选择机构"
      :top="marginTop"
      :visible.sync="dialogVisible"
      center
      :close-on-click-modal="false"
      width="500px"
    >
      <el-scrollbar class="groupScroll" style="text-align:left">
        <el-radio-group
          id="orgDialogRadio"
          v-model="selectOrg"
        >
          <el-input v-show="searchInputVisible" v-model="searchInput" class="orgInput" placeholder="请输入机构名" />
          <div v-for="(org, idx) in orgList" :key="idx" style="padding: 10px 0">
            <el-radio :label="org">{{ org.orgName }}</el-radio>
          </div>
        </el-radio-group>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel()">取 消</el-button>
        <el-button :disabled="!!selectOrg ? false : true" type="primary" @click="subLogin()">确 定</el-button>
      </span>
    </el-dialog>

    <!--    <el-dialog title="第三方登录" :visible.sync="showDialog">-->
    <!--      暂未开放! ! !-->
    <!--      <br>-->
    <!--      <br>-->
    <!--      <br>-->
    <!--      <social-sign />-->
    <!--    </el-dialog>-->

    <msg-dialog />
  </div>
</template>

<script>
import { validPassword } from 'ntr-ysb/utils/validate'
import { getToken, removeCaptcha } from '@/utils/token'
import { getMargin } from 'ntr-ysb/utils/validate'
import { getInfo, setInfo, removeInfo } from 'ntr-ysb/utils/info'
import { checkLogin, verifyCaptcha } from '@/api/login'
import msgDialog from '@/components/msgDialog'
import md5 from 'js-md5'

export default {
  name: 'Login',
  components: { msgDialog },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
      callback()
    }
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('请输入正确格式的密码'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      loginForm: {
        username: '',
        password: '',
        identification: ''
      },
      codeUrl: '/yos-user/auth/captcha', // 验证码地址
      passwordType: 'password',
      loginRules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        identification: this.identificationVisible === true ? [{ required: true, trigger: 'blur', message: '请输入验证码' }] : null
      },
      autoLogin: true, // 是否记住密码
      acActive: false, // 账号是否被激活
      pwActive: false, // 密码是否被激活
      codeActive: false, // 验证码是否被激活
      imgCodeSrc: '', // 验证码图片
      showDialog: false,
      orgList: [], // 机构列表
      selectOrg: '',
      marginTop: '',
      dialogVisible: false, // 选择机构弹框
      identificationVisible: false, // 是否显示验证码
      allOrgs: [],
      searchInputVisible: false,
      searchInput: ''
    }
  },
  watch: {
    dialogVisible(val) {
      // console.log(val)
      if (!val) {
        this.orgList = []
        this.selectOrg = []
        this.searchInputVisible = false
        this.searchInput = ''
        document.onkeydown = null
      } else {
        // 打开弹框时居中
        this.$nextTick(() => {
          this.$refs.orgDialog.$nextTick(() => {
            this.marginTop = getMargin(this, 'orgDialog')
          })

          // 默认选中第一个
          this.selectOrg = this.orgList.length ? this.orgList[0] : ''
          let selectOrgIndex = 0 // 初始化默认选中的机构索引
          // 弹框出现时监听回车事件---直接登陆
          const that = this
          const dom = document.getElementById('orgDialogRadio')
          if (dom) {
            dom.getElementsByTagName('input')[0].focus()
            dom.onkeydown = function(ev) {
              const event = ev || event
              switch (event.keyCode) {
                case 13:
                  // 弹框显示时触发登陆
                  if (that.dialogVisible) {
                    that.subLogin()
                  }
                  break
                case 38: {
                  selectOrgIndex--
                  if (selectOrgIndex < 0) {
                    selectOrgIndex = that.orgList.length - 1
                  }
                  that.selectOrg = that.orgList[selectOrgIndex]
                  break
                }
                case 40: {
                  selectOrgIndex++
                  if (selectOrgIndex > that.orgList.length - 1) {
                    selectOrgIndex = 0
                  }
                  that.selectOrg = that.orgList[selectOrgIndex]
                  break
                }
              }
            }
          }
        })
      }
    },
    searchInput(value) {
      this.orgList = []
      for (let i = 0; i < this.allOrgs.length; i++) {
        if (this.allOrgs[i].orgName.indexOf(value) > -1) {
          this.orgList.push(this.allOrgs[i])
        }
      }
      this.selectOrg = this.orgList[0]
    }
  },
  created() {
    this.checkLogin()
    // 从缓存中提取账号密码
    if (getInfo()) {
      const { username, password } = JSON.parse(getInfo())
      this.loginForm.username = username
      this.loginForm.password = password
    }
  },
  mounted() {},
  methods: {
    // 获取code
    getCode() {
      this.codeUrl = '/yos-user/auth/captcha?r=' + Math.random()
    },
    // 检查是否登录
    checkLogin() {
      checkLogin()
        .then(res => {
          const token = getToken()
          // 有token强制跳转至首页
          if (token) {
            this.$router.push({ path: this.redirect || '/' })
          }
        })
        .catch(() => {})
    },
    // 关闭弹框事件
    handleCancel() {
      this.dialogVisible = false
      this.orgList = []
      this.selectOrg = []
      this.searchInputVisible = false
      this.searchInput = ''
    },
    // 选择机构后登陆
    subLogin() {
      console.log(this.selectOrg)
      this.$store
        .dispatch('user/subLogin', this.selectOrg)
        .then(res => {
          this.$router.push({ path: this.redirect || '/' })
          // 路由跳转
          // console.log(res)
        })
        .catch(() => {})
    },
    /**
     * 提交数据
     **/
    submitData() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.identificationVisible === true) {
            // 请求登陆接口
            verifyCaptcha({ captcha: this.loginForm.identification }).then(_ => {
              this.doLogin()
            }).catch(err => {
              this.$message({
                type: 'error',
                message: err.message,
                showClose: true
              })
              this.identificationVisible = true
              this.getCode() // 登录失败重新获取code
              clearTimeout(this.timeout ? this.timeout : null)
              this.timeout = setTimeout(() => {
                this.identificationVisible = false
                this.loginForm.identification = ''
              }, 300000)
            })
              .finally(() => {
                this.loading = false
              })
          } else {
            removeCaptcha()
            this.doLogin()
          }
        } else {
          return false
        }
      })
    },
    // 登录
    doLogin() {
      this.$store
        .dispatch('user/login', Object.assign({}, this.loginForm, { password: md5(this.loginForm.password) }))
        .then(res => {
          // 是否记住密码
          if (this.autoLogin) {
            // 缓存账号密码
            const { username, password } = this.loginForm
            setInfo(JSON.stringify({ username, password }))
          } else {
            removeInfo()
          }
          // 只有一家店铺时直接跳转登陆
          if (res.length === 1) {
            this.selectOrg = res[0]
            this.subLogin()
          } else {
            this.orgList = res
            this.searchInputVisible = this.orgList.length > 10
            this.allOrgs = res
            this.dialogVisible = true
          }
        })
        .catch(err => {
          this.$message({
            type: 'error',
            message: err.message,
            showClose: true
          })
          this.identificationVisible = true
          this.getCode() // 登录失败重新获取code
          clearTimeout(this.timeout ? this.timeout : null)
          this.timeout = setTimeout(() => {
            this.identificationVisible = false
            this.loginForm.identification = ''
          }, 300000)
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * 切换显示密码
     */
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    /**
     * 账号失焦事件
     */
    acTextOnblur() {
      if (!this.loginForm.username) {
        this.acActive = false
      }
    },
    /**
     * 账号聚焦事件
     */
    acTextOnFocus() {
      this.acActive = true
    },
    /**
     * 密码失焦事件
     */
    pwTextOnblur() {
      if (!this.loginForm.password) {
        this.pwActive = false
      }
    },
    /**
     * 密码聚焦事件
     */
    pwTextOnFocus() {
      this.pwActive = true
    },
    /**
     * 验证码聚焦事件
     */
    codeTextOnFocus() {
      this.codeActive = true
    },
    /**
     * 验证码失焦事件
     */
    codeTextOnblur() {
      if (!this.loginForm.identification) {
        this.codeActive = false
      }
    },
    /**
     * 重新获取验证码
     */
    reGetCodeImg() {}
  }
}
</script>

<style lang="scss">
  @import '../../style/login';
</style>
